package com.threeonemeeting.activity;

import java.io.File;
import java.util.Map;

import android.app.NotificationManager;
import android.app.Service;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;

import com.snda.lib.http.HttpUtil;
import com.snda.lib.http.TaskManager;
import com.snda.lib.task.BaseAsyncTask;
import com.threeonemeeting.Const;
import com.threeonemeeting.DataCenter;
import com.threeonemeeting.R;
import com.threeonemeeting.activity.ext.PageListActivity;
import com.threeonemeeting.adapter.DownloadItemListAdapter;
import com.threeonemeeting.model.DownloadInfo;
import com.threeonemeeting.model.DownloadInfoList;
import com.threeonemeeting.task.DownloadDocumentFileTask;
import com.threeonemeeting.task.HttpConst;
import com.threeonemeeting.util.AppSettings;
import com.threeonemeeting.util.MiscUtil;

public class DownloadActivity extends PageListActivity implements
		OnItemClickListener {

	final static int MENU_ID_PAUSE = Menu.FIRST; // 暂停下载
	final static int MENU_ID_CANCEL = Menu.FIRST + 1; // 取消下载
	final static int MENU_ID_CONTINUE = Menu.FIRST + 2; // 继续下载
	final static int MENU_ID_DELETE_DOWNLOAD = Menu.FIRST + 3; //
	final static int MENU_ID_REDOWNLOAD = Menu.FIRST + 4; // 重新下载
	final static int MENU_ID_OPEN = Menu.FIRST + 5;

	// 下载文件列表
	private DownloadItemListAdapter downloadAdapter = null;

	// 通过Handler进行UI的更新
	Handler uiHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {

			// 更新
			case 0:

				if (downloadAdapter != null) {
					downloadAdapter.notifyDataSetChanged();
				}

				break;

			}
			super.handleMessage(msg);
		}
	};

	private void showListViewLayout(boolean bShow) {
		LinearLayout listViewLayout = (LinearLayout) findViewById(R.id.layout_listview);
		LinearLayout noRecordLayout = (LinearLayout) findViewById(R.id.layout_norecord);
		if (bShow == true) {
			if (listViewLayout != null) {
				listViewLayout.setVisibility(View.VISIBLE);
			}
			if (noRecordLayout != null) {
				noRecordLayout.setVisibility(View.GONE);
			}
		} else {
			if (listViewLayout != null) {
				listViewLayout.setVisibility(View.GONE);
			}
			if (noRecordLayout != null) {
				noRecordLayout.setVisibility(View.VISIBLE);
			}
		}
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ac_download_list, "");
		init("下载管理");
	}

	private Runnable refreshTask = new Runnable() {

		public void run() {
			uiHandler.sendEmptyMessage(0);
			uiHandler.postDelayed(this, Const.Times.SECOND * 2);
		}
	};

	private void continueDownloading(DownloadInfo dInfo) {
		if (dInfo == null)
			return;

		DownloadDocumentFileTask downloadTask = new DownloadDocumentFileTask(
				DownloadActivity.this, DownloadActivity.this);
		downloadTask.setUrl(dInfo.strFileUrl);
		downloadTask.setSavePath(AppSettings
				.getFilePath(getApplicationContext()));
		downloadTask.setContinue(true);
		downloadTask.setAppKey(dInfo.strAppKey);
		downloadTask.setFileTitle(dInfo.strFileTitle);

		TaskManager.continueTask(dInfo.nCookie, downloadTask, null, false);
		dInfo.nStatus = DownloadInfo.DOWNLOAD_STATUS_RUNNING;
		downloadAdapter.notifyDataSetChanged();
	}

	private void reDownloading(DownloadInfo dInfo) {
		if (dInfo == null)
			return;

		// 开始下载，则此时发送一个通知到通知栏
		NotificationManager updateNotificationManager = (NotificationManager) this
				.getApplicationContext().getSystemService(
						Service.NOTIFICATION_SERVICE);
		updateNotificationManager.cancel(dInfo.nCookie);

		DownloadInfoList listDownload = DataCenter.getInstance().listDownload;
		listDownload.deleteDownloadInfo(dInfo.strAppKey);
		DownloadDocumentFileTask downloadTask = new DownloadDocumentFileTask(
				DownloadActivity.this, DownloadActivity.this);
		downloadTask.setUrl(dInfo.strFileUrl);
		downloadTask.setSavePath(AppSettings
				.getFilePath(getApplicationContext()));
		downloadTask.setContinue(false);
		downloadTask.setAppKey(dInfo.strAppKey);
		downloadTask.setFileTitle(dInfo.strFileTitle);

		TaskManager.addTask(downloadTask, null, false);
		dInfo.nStatus = DownloadInfo.DOWNLOAD_STATUS_RUNNING;
		downloadAdapter.notifyDataSetChanged();
	}

	private void cancelDownloading(DownloadInfo dInfo) {
		if (dInfo != null) {

			BaseAsyncTask httpAsync = (BaseAsyncTask) TaskManager.getInstance()
					.getTask(dInfo.nCookie);
			if (httpAsync != null) {

				// 取消下载
				httpAsync.cancelTask();
				dInfo.nStatus = DownloadInfo.DOWNLOAD_STATUS_CANCEL;
				downloadAdapter.notifyDataSetChanged();
			}

			DataCenter.getInstance().getDB().addDownloadInfo(dInfo);
		}
	}

	private void FroceDelete(File _file) throws Exception {
		try {
			_file.delete();
		} catch (Exception e) {
			_file.deleteOnExit();
		} finally {
			if (_file.exists()) {
			}
		}
	}

	private void deleteDownload(DownloadInfo dInfo) {

		cancelDownloading(dInfo);

		File localFile = new File(dInfo.strLocalPath);
		try {
			FroceDelete(localFile);

		} catch (Exception e) {
		}

		DownloadInfoList downloadList = DataCenter.getInstance().listDownload;
		if (downloadList != null) {
			DataCenter.getInstance().listDownload
					.deleteDownloadInfo(dInfo.strAppKey);
		}

		downloadList = DataCenter.getInstance().listDownload;

		DataCenter.getInstance().getDB().deleteDownloadInfo(dInfo.strAppKey);
		downloadAdapter.notifyDataSetChanged();

		// 开始下载，则此时发送一个通知到通知栏
		NotificationManager updateNotificationManager = (NotificationManager) this
				.getApplicationContext().getSystemService(
						Service.NOTIFICATION_SERVICE);
		updateNotificationManager.cancel(dInfo.nCookie);

		int nCount = downloadAdapter.getCount();
		if (nCount == 0) {
			showListViewLayout(false);
		}
	}

	OnClickListener closeBtnClickListener = new OnClickListener() {

		public void onClick(View v) {
			finish();
		}
	};

	public void processDownloadFile(Map<String, Object> map) {

		Integer nError = (Integer) map.get(HttpUtil.KEY_ERROR_CODE);
		String strAppKey = (String) map.get("appkey");

		if (nError == null || nError != HttpUtil.ERROR_SUCCESS) {

			if (nError == HttpUtil.ERROR_ALREADY_EXIST) {

			} else {

				// 更新对应的状态为FAILED
				DownloadInfo dInfo = DataCenter.getInstance().listDownload
						.getDownloadInfo(strAppKey);
				if (dInfo != null) {
					dInfo.nStatus = DownloadInfo.DOWNLOAD_STATUS_FAILED;
				}
			}

			return;
		}

		// 正常状态下更新进度
		uiHandler.sendEmptyMessage(0);
	}

	public void doCallBack(Map<String, Object> map) {

		Integer msgType = (Integer) map.get(HttpConst.KEY_TASK_TYPE);
		if (msgType == null) {
			Log.d(Const.Tag, "can't find type in response type");
			return;
		}

		if (msgType == HttpConst.TASKTYPE_DOWNLOADAPKFILE) {
			processDownloadFile(map);
			return;
		}
	}

	// ItemClick事件
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		int nIndex = arg2;

		if (downloadAdapter == null || downloadAdapter.getCount() == 0)
			return;

		if (nIndex > downloadAdapter.getCount() - 1)
			return;

		DownloadInfo dInfo = downloadAdapter.getItem(nIndex);
		if (dInfo != null) {

			// 如果是正在下载，在修改为暂停下载
			if (dInfo.nStatus == DownloadInfo.DOWNLOAD_STATUS_RUNNING) {
				cancelDownloading(dInfo);

			} else if (dInfo.nStatus == DownloadInfo.DOWNLOAD_STATUS_CANCEL
					|| dInfo.nStatus == DownloadInfo.DOWNLOAD_STATUS_FAILED) {
				continueDownloading(dInfo);
			} else if (dInfo.nStatus == DownloadInfo.DOWNLOAD_STATUS_FINISHED) {

				String strApkPath = dInfo.strLocalPath;
				if (strApkPath != null) {
					MiscUtil.openDocument(this, strApkPath);
				}
			}
		}
	}
}
